home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 46 < prev    next >
Internet Message Format  |  1996-08-06  |  1KB

  1. Path: teal.csn.net!not-for-mail
  2. From: thads@csn.net (Thad Smith)
  3. Newsgroups: comp.std.c
  4. Subject: Re: Undefined result vs. int's holding undefined values.
  5. Date: 7 Jan 1996 15:41:47 -0700
  6. Organization: T3 Systems
  7. Message-ID: <oZA8wQ9ytpjN084yn@csn.net>
  8. References: <4ck70b$rd7@news.informix.com> <4ckms5$rd7@news.informix.com>
  9.  <4cmg0s$1mb@der.twinsun.com>
  10. Reply-To: ThadSmith@acm.org
  11. NNTP-Posting-Host: 199.117.27.22
  12.  
  13. In article <4cmg0s$1mb@der.twinsun.com>,
  14. eggert@twinsun.com (Paul Eggert) wrote:
  15. >This reminds me of a similar bug I found a long time ago when porting
  16. >the Modula-3 runtime, which contained code that acted something like this:
  17. >
  18. >    int sum_overflow (int x, int y) {
  19. >        return (x + y < x) != (y < 0);
  20. >    }
  21. >
  22. >The C Standard does not guarantee that the above function works,
  23. >since integer overflow leads to undefined behavior,
  24. >but when I found that the function did not work with whatever old version
  25. >of GCC I was using at the time, I reported it as a bug to the GCC maintainers
  26. >and got a fix from them in a few days.
  27. >
  28. >Regardless of what the C Standard says, it should be obvious that it's
  29. >crucial to have integer overflow checking working properly in an
  30. >application that needs it.  
  31.  
  32. I agree, but it is possible to rewrite the function so that it doesn't
  33. invoke undefined behavior:
  34.  
  35.   #include <limits.h>
  36.   int sum_overflow (int x, int y) {
  37.       return x > 0? (y > INT_MAX - x) : (y < INT_MIN - x);
  38.   }
  39.  
  40. Thad
  41.